// import Logo from '../../images/公告栏.png'
import Logo from '../../images/chat-logo.png'
import Identity from '../../images/教育局管理员.png'
import {
    lgAlert, LgSplitLine, LgDropdown, LgTopBarContainer, BackToOfficialBlock, LgTopTabs,
    IdentityBlock,
    LogoutBlock,
    MessageBlock,
    UserBlock, SystemInfo, createClassName, SystemInfoProps
} from "lancoo-web-ui";
import { getData, getQueryVariable } from "../../../../common/js/fetch";
import React, { Component } from "react";

import './index.scss'


const { classNames } = createClassName("lg-top-bar")
const { classNames: pageClassNames } = createClassName("lg-top-bar-example")


export class LgTopBarC extends Component {

    constructor(props) {
        super(props);
        // console.log('props', props);

        this.state = {
            currentTerm: '2021-2022学年第1学期',
            term: [
                { text: '2021-2022学年第1学期', value: 0 },
                { text: '2021-2022学年第2学期', value: 1 },
                { text: '2022-2023学年第1学期', value: 2 }
            ],
            photo: '',
            identity: '',
            isPreset: true,
            identityName: '',
            baseUrl: JSON.parse(sessionStorage.getItem('schoolSystemInfo')).baseUrl,
            userInfo: JSON.parse(sessionStorage.getItem('userInfo')),
            detailed: 0
        }
        this.backToOfficialPlatform = this.backToOfficialPlatform.bind(this)
        this.handLogout = this.handLogout.bind(this)
        this.handSelectOption = this.handSelectOption.bind(this)
    }

    //帮助
    openHelp() {
        console.log('window.location.href', window.location);
        //开发环境
        if (window.location.href.indexOf('http://localhost:300') === 0) {
            let origin = window.location.origin
            window.open(`${origin}/UserHelp/index.html?lg_tk=` + getQueryVariable('lg_tk') + '&lg_ic=' + getQueryVariable('lg_ic'), "_blank");
        } else {
            let href = window.location.href
            let index = href.indexOf('/html')
            let result = href.substring(0, index);
            window.open(`${result}/UserHelp/index.html?lg_tk=` + getQueryVariable('lg_tk') + '&lg_ic=' + getQueryVariable('lg_ic'), "_blank");
        }
    };

    openMessage = () => {
        document.getElementById('Assistant_infoCenter').click();
    }

    componentDidMount() {
        let isDetail = getQueryVariable('bulletinId') || 0;
        if (isDetail !== 0) {
            this.setState({
                detailed: 1
            })
        }
        //引入消息图标
        // let UEditorLooding = setInterval(() => {
        //     if (sessionStorage.getItem('PsnMgrLoading') == 1) {
        //         let PsnMgrLgAssistantAddr = sessionStorage.getItem('PsnMgrLgAssistantAddr');
        //         this.loadScriptOrCss([PsnMgrLgAssistantAddr + "/PsnMgr/LgAssistant/css/lancoo.cp.assistantInfoCenter.css",
        //         PsnMgrLgAssistantAddr + "/PsnMgr/LgAssistant/assets/jquery.pagination.js",
        //         PsnMgrLgAssistantAddr + "/PsnMgr/LgAssistant/js/lancoo.cp.assistantInfoCenter.js",
        //         ]);
        //         clearInterval(UEditorLooding);
        //     }
        // }, 500);
        this.setState({
            photo: JSON.parse(sessionStorage.getItem('userInfo')).photoPath
        })
        //获取用户身份
        let icCode = getQueryVariable('lg_ic')
        let identityInfos = JSON.parse(sessionStorage.getItem('userInfo')).identityInfos;
        if (icCode) {
            identityInfos && identityInfos.forEach(element => {
                if (icCode.indexOf(element.identityCode) !== -1) {
                    // console.log('element', element)
                    this.setState({
                        identity: element.iconUrl,
                        isPreset: element.isPreset,
                        identityName: element.identityName
                    })
                }
            });
        } else {
            this.setState({
                identity: identityInfos[0].iconUrl,
            })
        }
    }

    loadScriptOrCss(urlArr, num) {
        let $this = this;
        if (!num) {
            num = 0;
        }
        //正则判断是否是css;
        var reg = RegExp(/.css/);

        if (reg.test(urlArr[num])) {
            // 动态生成css
            var scriptOrCss = document.createElement('link');
            scriptOrCss.type = 'text/css';
            scriptOrCss.async = 'async';
            scriptOrCss.href = urlArr[num];
            scriptOrCss.rel = "stylesheet";
            document.getElementsByTagName("head")[0].appendChild(scriptOrCss);

        } else {
            // 动态生成js
            var scriptOrCss = document.createElement('script');
            scriptOrCss.type = 'text/javascript';
            scriptOrCss.async = 'async';
            scriptOrCss.src = urlArr[num];
            document.body.appendChild(scriptOrCss);
        }
        if (scriptOrCss.readyState) {
            //IE下
            scriptOrCss.onreadystatechange = function () {
                if (scriptOrCss.readyState === 'complete' || scriptOrCss.readyState === 'loaded') {
                    scriptOrCss.onreadystatechange = null;
                    num++;
                    if (num === urlArr.length) {
                        return;
                    } else {
                        $this.loadScriptOrCss(urlArr, num);
                    }
                }
            }
        } else {
            //其他浏览器
            scriptOrCss.onload = function () {
                num++;
                if (num === urlArr.length) {
                    return;
                } else {
                    $this.loadScriptOrCss(urlArr, num);
                }
            }
        }
    }

    gotoPersonalMgr = () => {//跳转用户信息
        let edu = getQueryVariable('edu')
        let token = sessionStorage.getItem('token')
        let baseUrl = this.state.baseUrl;
        if (edu) {
            window.open(baseUrl + '/UserMgr/PersonalMgr/Default.aspx?lg_tk=' + token, '_blank');
        } else {
            window.open(baseUrl + '/html/personalMgr/', '_blank');
        }
    }

    backToOfficialPlatform = () => {//返回办公平台
        let edu = getQueryVariable('edu');
        let userType = sessionStorage.getItem('userInfo').userType;
        let userClass = sessionStorage.getItem('userInfo').userClass;
        let token = sessionStorage.getItem('token');
        let baseUrl = this.state.baseUrl;
        if (edu) {
            if (userType == 6 && userClass == 2) {
                window.open(baseUrl + '/Index_A_aspx?lg_tk=' + token, '_blank');
            }
        } else {
            window.open(baseUrl, '_self');
        }
    }

    showMessageBlock = () => {//打开消息中心
        console.log('打开消息中心')
    }

    handLogout = () => {
        let baseUrl = this.state.baseUrl;
        lgAlert.show({ tipType: 'closeAll' })
        let alert = lgAlert.show({
            duration: 0,
            content: '确定要退出登录吗？ ',
            isShowCloseBtn: true,
            tipType: 'question',
            tipMouldType: 'A',
            tipSize: 'small',
            description: `You should be self-esteem, do not be arrogant`,
            position: {
                xAxis: 'center',
                yAxis: 'center'
            },
            onConfirm() {
                // lgAlert.show({ tipType: 'closeAll' })
                getData('api/commons/school/user/logout', {
                    token: sessionStorage.getItem('token')
                }).then(data => {
                    return data.json()
                }).then(json => {
                    if (json.code == '200') {
                        let url = window.location.href;
                        url = url.split('?');
                        if (url.length > 1 && url[1].indexOf('&') > -1) {
                            let pram = url[1].split('&');
                            url = url[0] + '?';
                            pram.map((item) => {
                                if (item.indexOf('lg_tk=') === -1) {
                                    url += item + '&';
                                }
                            })
                            url.slice(0, url.length - 1);
                        } else {
                            url = url[0];
                        }
                        if (url.slice(-2) === '#/') {
                            url = url.slice(0, -2);
                        }
                        console.log(url);
                        url = encodeURIComponent(url);
                        sessionStorage.removeItem('token');
                        // alert(  this.state.data.baseUrl +'/UserMgr/Login/Login.aspx?lg_sysid='+this.state.data.SysID+'&lg_preurl='+url)\
                        window.open(baseUrl, '_self');
                    }
                })
            },
            onCancel(type, positionIndex) {

            },
        });
    }


    handSelectOption(item, index) {
        this.setState({ currentTerm: item.text })
        console.log("选择的option:", item, "\nindex:", index)
    }

    render() {
        let {
            identity,
            photo,
            userInfo,
            detailed,
            isPreset,
            identityName
        } = this.state
        const systemInfos = [{
            type: 'A',
            logoUrl: Logo,
            systemName: "在线交流",
            // subSystemName: detailed == 1 ? '公告详情' : '',
            // role: sessionStorage.getItem('isManage') === '1' ? '管理端' : '个人端',
            // version: detailed == 1 ? '公告详情' : '',
            // subSystemName: sessionStorage.getItem('isManage') === '1' ? '管理端' : '个人端',
        },
            // , {
            //     type: 'C',
            //     logoUrl: Logo,
            //     systemName: "访客管理",
            //     children: (
            //         <LgTopTabs tabs={
            //             [
            //                 {label: '首页', value: 0, selected: true},
            //                 {label: '菜单1', value: 1, selected: false},
            //                 {label: '菜单2', value: 2, selected: false},
            //                 {label: '菜单3', value: 3, selected: false},
            //             ]
            //         }/>)
            // },
            //  {
            //     type: 'C',
            //     logoUrl: Logo,
            //     systemName: "访客管理",
            //     subSystemName: '测试统分',
            // }
        ]
        const systemInfoLabels = ['基本用法', '产品名+版本', '产品名+用户端', '产品名+学期', '产品名+版本+用户端', '产品名+版本+用户端', '产品名+用户端+学期', '产品名+版本+用户端+学期']


        return (
            <>
                {
                    systemInfos.map((item, index) => (
                        <div className={(pageClassNames("row"))} key={'systemInfo' + index}>
                            {/* <div className={(pageClassNames("row-label"))}>{systemInfoLabels[index]}</div> */}
                            <div className={(pageClassNames("row-value"))}>
                                <LgTopBarContainer className={this.props.className} type="C">

                                    <SystemInfo {...item} />

                                    <div className={(classNames("right"))}>

                                        {/* <BackToOfficialBlock handClick={this.backToOfficialPlatform} /> */}

                                        {/* <LgSplitLine margin={'0 10px'} /> */}

                                        {/* <MessageBlock handClick={this.showMessageBlock} id="Assistant_infoCenter" /> */}
                                        {/* <div className='help'  >
                                            <div id="Assistant_infoCenter" className='message-icon'></div>
                                            <span onClick={this.openMessage}>消息</span>
                                        </div>
                                        {
                                            sessionStorage.getItem('isManage') === '1' ?
                                                <div className='help' onClick={this.openHelp}>
                                                    <i className='help-icon'></i>
                                                    <span >帮助</span>
                                                </div>
                                                : ''
                                        } */}

                                        {/* <LgSplitLine margin={'0 10px'} /> */}

                                        <div className='userinfo' onClick={this.gotoPersonalMgr} >
                                            <UserBlock userImageUrl={photo} userName={userInfo.userName} />
                                        </div>

                                        <IdentityBlock identityImgUrl={identity ? identity : Identity}>
                                            {
                                                !isPreset ?
                                                    <span className={(classNames("define-identity"))} title={identityName} >{identityName}</span>
                                                    : ''
                                            }
                                        </IdentityBlock>

                                        {/* <LogoutBlock handClick={this.handLogout} /> */}

                                    </div>

                                </LgTopBarContainer>
                            </div>
                        </div>

                    ))
                }
            </>

        );
    }
}

// export const LgTopBarCodeC = code
export default LgTopBarC;
